<?php

namespace Common\DeviceTcp;

use Common\BaseTable;
use Common\Helpers\DebugHelper;
use Common\Plugin\PluginManager\PluginTcpManager;
use Hyperf\Contract\OnReceiveInterface;
use Hyperf\Di\Annotation\Inject;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\SimpleCache\CacheInterface;
use Swoole\Coroutine\Channel;
use function Swoole\Coroutine\go;

class DeviceTcpService  implements OnReceiveInterface
{
    /**
     * @Inject
     * @var EventDispatcherInterface
     */
    #[Inject]
    protected EventDispatcherInterface $eventDispatcher;

    /**
     * @Inject
     * @var CacheInterface
     */
    #[Inject]
    protected CacheInterface $cache;


    private PluginTcpManager $pluginTcpManager;

    public function  onConnect(): void
    {
        echo '设备-onConnect-DeviceTcpService'.PHP_EOL;
        BaseTable::getInstance();
        $this->pluginTcpManager = new pluginTcpManager();
        $this->pluginTcpManager->loadPluginsFromDirectory(__DIR__ . '/../../addons');
    }

    /**
     *
     * @param $server
     * @param int $fd
     * @param int $reactorId
     * @param string $data
     */
    public function onReceive($server, int $fd, int $reactorId, string $data): void
    {
        echo '设备上报-onReceive'.PHP_EOL;
        // 直接将数据分发给插件管理器
        $this->pluginTcpManager->handle($server, $fd, $reactorId, $data);
    }
}